/*
 * @Author: your name
 * @Date: 2021-04-29 16:16:02
 * @LastEditTime: 2021-09-16 10:01:53
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \saas\utils\utils.js
 */

/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timeout = null;

function debounce(func, wait = 500, immediate = false) {
    // 清除定时器
    if (timeout !== null) clearTimeout(timeout);
    // 立即执行，此类情况一般用不到
    if (immediate) {
        var callNow = !timeout;
        timeout = setTimeout(function() {
            timeout = null;
        }, wait);
        if (callNow) typeof func === "function" && func();
    } else {
        // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
        timeout = setTimeout(function() {
            typeof func === "function" && func();
        }, wait);
    }
}

/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timer, flag;

function throttle(func, wait = 500, immediate = true) {
    if (immediate) {
        if (!flag) {
            flag = true;
            // 如果是立即执行，则在wait毫秒内开始时执行
            typeof func === "function" && func();
            timer = setTimeout(() => {
                flag = false;
            }, wait);
        }
    } else {
        if (!flag) {
            flag = true;
            // 如果是非立即执行，则在wait毫秒内的结束处执行
            timer = setTimeout(() => {
                flag = false;
                typeof func === "function" && func();
            }, wait);
        }
    }
}

// 深度克隆
// 判断arr是否为一个数组，返回一个bool值
function deepClone(obj) {
    function isArray(arr) {
        return Object.prototype.toString.call(arr) === "[object Array]";
    }
    // 对常见的“非”值，直接返回原来值
    if ([null, undefined, NaN, false].includes(obj)) return obj;
    if (typeof obj !== "object" && typeof obj !== "function") {
        //原始类型直接返回
        return obj;
    }
    var o = isArray(obj) ? [] : {};
    for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
            o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
        }
    }
    return o;
}
// toast
function toast(title, duration = 1500, isSuccess) {
    isSuccess
        ?
        uni.showToast({
            title: title,
            icon: "success",
            duration: duration,
        }) :
        uni.showToast({
            title: title,
            icon: "none",
            duration: duration,
        });
}

// 邮箱验证
function isEmailAvailable(emailInput) {
    const regEmail =
        /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; //验证邮箱正则
    if (!regEmail.test(emailInput)) {
        return false;
    } else {
        return true;
    }
}

module.exports = {
    debounce,
    throttle,
    toast,
    deepClone,
    isEmailAvailable,
    //js显示早上好下午好晚上好
    getTimeState() {
        // 获取当前时间
        let timeNow = new Date();
        // 获取当前小时
        let hours = timeNow.getHours();
        // 设置默认文字
        let text = ``;
        // 判断当前时间段
        if (hours >= 0 && hours <= 10) {
            text = `早上好`;
        } else if (hours > 10 && hours <= 14) {
            text = `中午好`;
        } else if (hours > 14 && hours <= 18) {
            text = `下午好`;
        } else if (hours > 18 && hours <= 24) {
            text = `晚上好`;
        }
        // console.log(`hours >>>>>`, hours);
        // console.log(`text >>>>`, text);
        // 返回当前时间段对应的状态
        return text;
    },
    //判断string、object是否为空
    isEmpty(varvar) {
        if (varvar == undefined || varvar == null || !varvar) {
            return true;
        }
        if (typeof varvar == "string") {
            if (varvar.length == 0) {
                return true;
            } else {
                return false;
            }
        } else if (typeof varvar == "object") {
            for (var key in varvar) {
                return false;
            }
            return true;
        }
    },
    // 切换时间格式 2021-07-24 11:32:01 为7月24日 10:19
    needDate(time) {
        const date = new Date(Date.parse(time.replace(/-/g, "/")));

        var year = date.getFullYear() + "年";
        var month = date.getMonth() + 1 + "月";
        var day = date.getDate() + "日";
        var hh = date.getHours() + ":";
        var mm = date.getMinutes();
        var ss = date.getSeconds();
        mm = mm.toString().length < 2 ? "0" + mm : mm;
        return month + day + " " + hh + mm;
    },
    // 标准时间转多少分钟之前
    //2021-04-16 15:53:07
    putDate(time, type = "state") {
        if (!time) {
            return "--";
        }
        const date = Date.parse(time.replace(/-/g, "/"));
        // 时间字符串转时间戳
        var timestamp = new Date(date).getTime();

        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var month = day * 30;
        var year = day * 365;
        var now = new Date().getTime();
        var diffValue = now - timestamp;
        var result;
        if (diffValue < 0) {
            return;
        }
        var yearC = diffValue / year;
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;
        if (yearC >= 1) {
            result = "" + parseInt(yearC) + "年前";
        } else if (monthC >= 1) {
            result = "" + parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            result = "" + parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            result = "" + parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            result = "" + parseInt(hourC) + "小时前";
        } else if (minC >= 5) {
            result = "" + parseInt(minC) + "分钟前";
        } else {
            switch (type) {
                case "state":
                    result = "刚刚活跃";
                    break;
                case "default":
                    result = "刚刚";
                    break;
                case "file":
                    result = "刚刚上传";
                    break;
            }
        }
        return result;
    },
    // 标准时间转时间挫 //2021-08-12 10:2 to 1627698586
    dateToTimestamp(time) {
        const date = new Date(Date.parse(time.replace(/-/g, "/")));
        return Date.parse(date);
    },
    //比较版本号
    compareVersion(v2, v1 = wx.getSystemInfoSync().SDKVersion) {
        console.log("当前版本号", wx.getSystemInfoSync().SDKVersion);
        v1 = v1.split(".");
        v2 = v2.split(".");
        const len = Math.max(v1.length, v2.length);

        while (v1.length < len) {
            v1.push("0");
        }
        while (v2.length < len) {
            v2.push("0");
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i]);
            const num2 = parseInt(v2[i]);

            if (num1 > num2) {
                return true;
            } else if (num1 < num2) {
                return false;
            }
        }

        return false;
    },
    //获取当前时间 格式：2013-01-01  //00:00:00
    curentTime() {
        var now = new Date();

        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();

        var hh = now.getHours();
        var mm = now.getMinutes();

        var clock = year + "-";

        if (month < 10) clock += "0";

        clock += month + "-";

        if (day < 10) clock += "0";

        clock += day + " ";

        /* if (hh < 10) clock += "0";

        clock += hh + ":";
        if (mm < 10) clock += "0";
        clock += mm; */
        return clock;
    },
    //时间戳转换方法    date:时间戳数字 2013-01-01 00:00:00
    formatDate(date) {
        var date = new Date(date);
        var YY = date.getFullYear() + "-";
        var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
        var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
        var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return YY + MM + DD + " " + hh + mm + ss;
    },
    // 对象转string
    toStr(obj) {
        return encodeURIComponent(JSON.stringify(obj));
    },
    // string转对象
    toObj(str) {
        return JSON.parse(decodeURIComponent(str));
    },
    //一键复制
    copy(copyObject, text) {
        uni.setClipboardData({
            data: copyObject,
            success: (data) => {
                uni.showToast({
                    title: text || "复制成功",
                    icon: "success",
                    mask: false,
                });
            },
        });
    },
    //拨打电话
    openPhone(number) {
        if (!number) {
            return;
        }
        uni.makePhoneCall({
            phoneNumber: number,
        });
    },
    /**
     * @description: 预览图片
     * @param {Array} imgList
     * @return {*}
     */
    lookImg(imgList, current) {
        uni.previewImage({
            current: current || 0,
            urls: imgList,
        });
    },
    //查看欢迎语详情
    looking(type, url) {
        switch (type) {
            case "link":
                this.$utils.noWebUrl(url);
                return "";
            case "image":
                this.$utils.lookImg([url]);
                return "";
            case "miniprogram":
                this.navTo("/" + url);
                return "wx";
            case "video":
                this.navTo(`/pagesYzhVideo/video/playVideo?video=${url.replace("?vframe/jpg/offset/0", "")}`);
                return "video";
        }
    },
    // 打不开外链
    noWebUrl(url) {
        uni.showModal({
            title: "这是一个外部链接",
            content: "小程序暂不支持打开外部链接,可点击复制链接后在浏览器粘贴查看",
            confirmText: "复制链接",
            // confirmColor: store.getters.globalColor,
            success: (res) => {
                if (res.confirm) {
                    this.copy(url);
                } else if (res.cancel) {
                    console.log("用户点击取消");
                }
            },
        });
    },
    // 获取当前页面options参数
    getOptions() {
        // 获取页面参数
        const vm = getCurrentPages()[getCurrentPages().length - 1]; //当前页面实例
        return vm.options;
    },
    // 获取上一页页面实例
    beforeVm(page = 1) {
        return getCurrentPages()[getCurrentPages().length - (page + 1)].$vm; //当前页面实例
    },
    // 获取当前页面实例
    getVm() {
        return getCurrentPages()[getCurrentPages().length - 1].$vm; //当前页面实例
    },

    //be 赋值给 accept  去除掉accept中没有的值
    copyObj(accept, be) {
        Object.keys(accept).forEach((key) => {
            Object.keys(be).forEach((key2) => {
                if (key == key2) {
                    accept[key] = be[key2];
                }
            });
        });
    },
};
